<!-- 人事-待签署合同-确认签署 -->
<template>
  <ContentCard v-if="userId">
    <template #header>
      <pageHeaderNew :title="title" showBack> </pageHeaderNew>
    </template>
    <main>
      <a-form
        ref="refForm"
        autoLabelWidth
        :model="formData.data"
        :rules="rules"
      >
        <section>
          <header>
            <span>合同信息</span>
          </header>
          <div class="content">
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="合同编号" show-colon>
                  <a-input v-model="formData.data.contractNum" disabled />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item show-colon label="合同名称">
                  <a-input v-model="formData.data.contractName" disabled />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="合同类型" show-colon>
                  <a-input v-model="formData.data.groupTypeName" disabled />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item show-colon label="合同签约公司">
                  <a-input v-model="formData.data.companyName" disabled />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="合同开始日期" show-colon field="startTime">
                  <a-date-picker v-model="formData.data.startTime" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item show-colon label="合同结束日期" field="endTime">
                  <a-date-picker v-model="formData.data.endTime" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="合同签订日期" show-colon field="doneTime">
                  <a-date-picker v-model="formData.data.doneTime" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item show-colon label="合同期限">
                  <a-input v-model="formData.data.remindTime" disabled />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="合同状态" show-colon>
                  <a-select v-model="formData.data.status" disabled>
                    <a-option
                      v-for="item in contractUserStatus"
                      :value="item.value"
                      :label="item.text"
                      :key="item.value"
                    />
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item show-colon label="合同到期提醒">
                  <a-switch
                    v-model="formData.data.remindTime"
                    :checked-value="1"
                    :unchecked-value="2"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item label="合同备注" show-colon>
                  <a-textarea
                    v-model="formData.data.remark"
                    show-word-limit
                    :max-length="300"
                    allow-clear
                    :auto-size="{ minRows: 3 }"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="合同/协议附件" show-colon>
                  <!-- <a-upload
                    :default-file-list="formData.data.contractFileList"
                    action="http://192.168.0.178:30058/lke_file"
                    @before-remove="beforeRemove"
                    @success="onSuccess"
                    draggable
                    tip="请上传JPG、JPEG、PNG、DOC、DOCX、PDF、EXCEL、XLSX、XLS格式"
                    accept="image/png, image/jpeg, image/jpg, .doc, .docx, .pdf, .xls, .xlsx"
                  /> -->
                  <UploadFile
                    ref="uploadRef"
                    v-model:fileList="headFile"
                    :draggable="true"
                    :tip="`请上传${[
                      '.png',
                      '.jpeg',
                      '.jpg',
                      '.doc',
                      '.docx',
                      '.pdf',
                      '.xls',
                      '.xlsx'
                    ].join(',')}格式`"
                    :fileTypeList="[
                      '.png',
                      '.jpeg',
                      '.jpg',
                      '.doc',
                      '.docx',
                      '.pdf',
                      '.xls',
                      '.xlsx'
                    ]"
                    :userId="userId"
                    :type="6"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </div>
        </section>
      </a-form>
    </main>
    <footer>
      <a-space>
        <a-button style="" @click="$router.go(-1)">返回</a-button>
        <a-button type="primary" @click="save">保存</a-button>
      </a-space>
    </footer>
  </ContentCard>
</template>

<script lang="ts" setup>
import {
  GetUserContractByStatusDetail,
  ConfirmWaitSignedContractSign,
  ChangeConfirmWaitSignedContractSign,
  GetConfirmWaitSignedContractSignFile,
  ChangeWaitSignedContractState,
  EditContractStatus
} from '@/apis/management/contract/contractManagement/waitSigned';
import {
  GetUserRenewCommunicate,
  EditUserRenewCommunicate,
  EditUserRenewState
} from '@/apis/management/contract/baseSetting';
import {
  contractStatusToUserStatus,
  contractUserStatus
} from '@/utils/dictionary/contract';
import { GetLegalEntityList } from '@/apis/management/organization/organizationManagement/LegalEntity/index';
import { GetContractGroup } from '@/apis/management/contract/baseSetting';
import { GetBusinessModalData } from '@/apis/controltotal';
import { PostFile } from '@/apis/management/base';
import { Message, Modal } from '@arco-design/web-vue';
import { changeControlData } from '@/utils/control';
import { cloneDeep } from 'lodash';

// const userId = Number(localStorage.getItem('userId') as any);
const router = useRouter();
const route = useRoute();
const title = '确认签署';
const fileTypeList = [
  '.png',
  '.jpeg',
  '.jpg',
  '.doc',
  '.docx',
  '.pdf',
  '.xls',
  '.xlsx'
];
const userId = +route.query.userId;
let refForm = ref();
const formData = reactive<any>({
  data: {
    companyId: undefined, // 签约公司
    contractNum: '', // 合同编号
    contractName: '', // 合同名称
    doneTime: '', // 合同签订时间
    endTime: '', // 合同结束日期
    expire: '', // 确认截止日期未确认将视为 1默认通过 2不通过
    overTime: '', // 签署日期
    remark: '', // 备注
    remind: '', // 提醒天数
    remindTime: '', // 提醒日期
    signature: '', // 合同签署有效日期
    startTime: '', // 合同开始日期
    status: '', // 合同状态
    typeId: undefined, // 合同类型
    userId: '', // 人员id
    way: 1, // 签署方式 1在线签署 2线下签署
    contractFileList: []
  }
});

const rules = {
  companyId: [
    {
      required: true,
      message: '请选择签约公司'
    }
  ],
  contractNum: [
    {
      required: true,
      message: '请输入合同编号'
    }
  ],
  contractName: [
    {
      required: true,
      message: '请输入合同名称'
    }
  ],
  doneTime: [
    {
      required: true,
      message: '请选择合同签订时间'
    }
  ],
  endTime: [
    {
      required: true,
      message: '请选择合同结束日期'
    }
  ],
  startTime: [
    {
      required: true,
      message: '请选择合同开始日期'
    }
  ]
};

let lawList = ref([]); // 储存企业签署方数据
let groupList = ref([]); // 合同类型分组数据
let controlList = ref([]); // 储存控件数据
// 获取数据
const getData = async () => {
  try {
    const [
      contractDetailRes,
      contractDetailFileRes,
      lawListRes,
      groupListRes,
      controlListRes
    ] = await Promise.all([
      GetUserContractByStatusDetail({
        userId: userId,
        status: 5
      }),
      GetConfirmWaitSignedContractSignFile({
        id: userId,
        typeId: formData.data.id
      }),
      GetLegalEntityList({
        pageNumber: 0,
        pageSize: -1
      }),
      GetContractGroup({
        pageNumber: 0,
        pageSize: -1
      }),
      GetBusinessModalData({
        funcCode: 'SER_FUNC751D0BFF5DF442209D437EE9A581693E'
      })
    ]);
    formData.data = contractDetailRes[0];
    formData.data.contractFileList = contractDetailFileRes;
    lawList.value = lawListRes.content;
    groupList.value = groupListRes.content;
    formData.data.companyName = switchId2Name(
      lawList.value,
      formData.data.companyId
    );
    formData.data.groupTypeName = switchId2Name(
      flattenData(groupList.value),
      formData.data.typeId
    );
    controlList.value = changeControlData(
      controlListRes.funcCtlInfos,
      'ctlDetail'
    );
  } catch (error: unknown) {
    console.log(error);
  }
};
getData();

let headFile = computed({
  get() {
    return formData.data.contractFileList.length
      ? formData.data.contractFileList.map((item) => {
          return {
            uid: item.uid,
            fileId: item.id,
            fileUrl: item.url,
            fileName: item.name
          };
        })
      : [];
  },
  set(val) {
    formData.data.contractFileList = val.map((ele: any) => {
      return {
        name: ele.fileName,
        userId,
        id: ele.id,
        url: ele.fileUrl,
        uid: ele.uuid,
        listId: formData.data.id
      };
    });
    console.log('上传后业务获取', formData.data);
  }
});

// 将含有children的数据进行扁平化
const flattenData = (data: any) => {
  let result = [];
  for (let item of data) {
    if (item.children) {
      result.push(item.children);
      // result = result.concat(flattenData(item.children));
      result = [...result, flattenData(item.children)];
    }
  }
  return result.flat(Infinity);
};

// 将合同签约公司id转换为合同签约公司名称;
const switchId2Name = (list: any, id: number) => {
  let name = '';
  list.find((el: any) => {
    if (el.id === id) {
      name = el.name;
    }
  });
  return name;
};

// 成功上传文件
const onSuccess = async (fileItem: any) => {
  try {
    const res = await PostFile({
      file: fileItem.file
    });
    formData.data.contractFileList.push({
      name: fileItem.file.name,
      userId,
      url: res,
      uid: fileItem.uid,
      listId: formData.data.id
    });
  } catch (error: any) {
    console.log(error);
  }
};

const beforeRemove = (file) => {
  return new Promise((resolve, reject) => {
    Modal.confirm({
      title: '确定删除已上传的文件吗？',
      content: `确认删除 ${file.name}`,
      onOk: () => {
        let ind = formData.data.contractFileList.findIndex(
          (item: any) => item.uid === file.uid
        );
        formData.data.contractFileList.splice(ind, 1);
        resolve(true);
      },
      onCancel: () => reject('取消删除')
    });
  });
};
const uploadRef = ref();

// 将控件名字转换成控件code

// 保存
const save = async () => {
  try {
    // const res2 = await uploadRef.value.submit();
    // if (await refForm.value?.validate()) {
    //   return;
    // }
    // console.log('res2', uploadRef.value.uploadList);

    // await ConfirmWaitSignedContractSign({
    //   contractFileList: formData.data.contractFileList || []
    // });
    if (formData.data.isChang === 1) {
      let res: any = await GetUserContractByStatusDetail({
        userId: userId,
        status: 6
      });
      if (res?.length) {
        await EditContractStatus({
          id: res[0].id,
          status: 9
        });
      }
    }

    let requestList = [
      ChangeConfirmWaitSignedContractSign({
        id: formData.data.id,
        remark: formData.data.remark,
        doneTime: formData.data.doneTime,
        endTime: formData.data.endTime,
        startTime: formData.data.startTime
      }),
      ChangeWaitSignedContractState({
        id: userId,
        status: 10
      }),
      EditContractStatus({
        id: formData.data.id,
        status: 6
      }),
      EditUserRenewState({ id: userId, type: 4 })
    ];
    Message.success('签署成功');
    await Promise.all(requestList);
    router.back();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 取消
const cancel = () => {
  router.back();
};
</script>

<style scoped lang="less">
main {
  section {
    header {
      font-weight: 700;
      height: 56px;
      line-height: 56px;
      margin-bottom: 20px;
      &::before {
        margin-left: 10px;
        content: '';
        display: inline-block;
        width: 6px;
        height: 40%;
        margin-right: 10px;
        background: #165dff;
        position: relative;
        top: 7px;
        border-radius: 3px;
      }
    }
    .content {
    }
  }
}
footer {
  height: 100px;
  width: calc(100% - 100px);
  background-color: #fff;
  box-shadow: 1px -1px 10px 0 #cacaca;
  position: fixed;
  bottom: 0;
  left: 10%;
  display: flex;
  justify-content: center;

  .btn {
    width: 120px;
    height: 40px;
    border-radius: 5px;
  }
}

:deep(.arco-input-append) {
  background-color: #eee;
}
</style>
